<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="分类名称" prop="productName">
              <el-input v-model="queryParams.categoryName" placeholder="请输入产品分类名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @keyup.enter="handleQuery">
                <el-option v-for="dict in iot_product_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" plain icon="Plus" @click="handleAdd"
                v-hasPermi="['iot:product:add']">新增</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card style="padding-bottom:100px;">
      <el-row :gutter="30" v-loading="loading">
        <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in productList" :key="index"
          style="margin-bottom:30px;text-align:center;">
          <el-card :body-style="{ padding: '20px' }" shadow="always" class="card-item">
            <el-row type="flex" :gutter="10" justify="space-between">
              <el-col :span="20" style="text-align:left;">
                <el-link :underline="false"
                  style="font-weight:bold;font-size:16px;line-height:32px;white-space:nowrap;">
                  <svg-icon icon-class="product" /> {{ item.productName }}
                  <el-tag type="info" style="margin-left:5px;font-weight:200" v-if="item.isSys == 1">系统</el-tag>
                </el-link>
              </el-col>
              <el-col :span="4">
                <el-tooltip class="item" effect="dark" content="取消发布" placement="top-start" v-if="item.status == 2">
                  <el-button type="success" style="padding:5px;">已发布</el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="现在发布" placement="top-start" v-if="item.status == 1">
                  <el-button type="info" style="padding:5px;">未发布</el-button>
                </el-tooltip>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="14">
                <el-descriptions :column="1" size="small" style="margin-top:10px;white-space:nowrap;"
                  class="custom-descriptions">
                  <el-descriptions-item label="所属分类">
                    <el-link type="primary" :underline="false">{{ item.categoryName }}</el-link>
                  </el-descriptions-item>
                  <el-descriptions-item label="产品类型">
                    <dict-tag :options="iot_data_type" :value="item.deviceType" class="custom-tag-group" />
                  </el-descriptions-item>
                  <el-descriptions-item label="联网方式">
                    <dict-tag :options="iot_network_method" :value="item.networkMethod" class="custom-tag-group" />
                  </el-descriptions-item>
                  <el-descriptions-item label="设备授权">
                    <el-tag type="success" size="small" v-if="item.isAuthorize == 1">已启用</el-tag>
                    <el-tag type="info" size="small" v-else>未启用</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
              <el-col :span="10">
                <div style="margin-top:10px;">
                  <el-image style="width:100%;height:100px;border-radius:10px;" lazy
                    :preview-src-list="[item.imgUrlUrl]" :src="item.imgUrlUrl" fit="cover"
                    v-if="item.imgUrlUrl != null && item.imgUrlUrl != ''"></el-image>

                </div>
              </el-col>
            </el-row>
            <el-button-group style="margin-top:15px;height:28px;">
              <el-button size="small" type="primary" icon="el-icon-view" @click="handleUpdate(item)"
                v-hasPermi="['iot:product:query']">详情</el-button>
              <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDelete(item)"
                v-hasPermi="['iot:product:remove']" v-if="item.status == 1">删除</el-button>
            </el-button-group>
          </el-card>
        </el-col>
      </el-row>

      <el-empty description="暂无数据，请添加产品" v-if="total == 0"></el-empty>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        :pageSizes="[12, 24, 36, 60]" @pagination="getList" />

      <!-- 下载SDK -->
      <el-dialog width="500px" append-to-body>
        <el-link type="danger" style="padding-left:10px;" :underline="false">该功能暂未实现，参考教程和项目的SDK示例</el-link>
        <el-form label-width="80px">
          <el-form-item label="设备类型">
            <el-radio-group>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" disabled>下 载</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script setup name="Product" lang="ts">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from '@/api/iot/product';
import { ProductVO, ProductQuery, ProductForm } from '@/api/iot/product/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_product_status, iot_data_type, iot_network_method } = toRefs<any>(proxy?.useDict('iot_product_status', 'iot_data_type', 'iot_network_method'));
const productList = ref<ProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProductForm = {
  productId: undefined,
  productName: undefined,
  protocolCode: undefined,
  categoryId: undefined,
  categoryName: undefined,
  isSys: undefined,
  isAuthorize: undefined,
  mqttAccount: undefined,
  mqttPassword: undefined,
  mqttSecret: undefined,
  status: undefined,
  thingsModelsJson: undefined,
  deviceType: undefined,
  networkMethod: undefined,
  vertificateMethod: undefined,
  transport: undefined,
  imgUrl: undefined,
  remark: undefined
}
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: undefined,
    categoryName: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "产品分类ID不能为空", trigger: "change" }
    ],

    isSys: [
      { required: true, message: "是否系统通用不能为空", trigger: "change" }
    ],
    isAuthorize: [
      { required: true, message: "是否启用授权码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProduct(queryParams.value);
  productList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  productFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductVO[]) => {
  ids.value = selection.map(item => item.productId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: 'productEdit' });
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ProductVO) => {
  reset();
  const _productId = row?.productId || ids.value[0]
  router.push({ path: 'productEdit', query: { productId: _productId} });
}


/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.productId) {
        await updateProduct(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addProduct(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProductVO) => {
  const _productIds = row?.productId || ids.value;
  await proxy?.$modal.confirm('是否确认删除产品管理编号为"' + _productIds + '"的数据项？').finally(() => loading.value = false);
  await delProduct(_productIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('iot/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  console.log("onMounted");
  getList();
});
</script>
<style lang="scss" scoped>
.card-item {
  border-radius: 15px;
}

.custom-descriptions .el-descriptions__content {
  display: flex;
  align-items: center;
}

.custom-tag-group {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}
</style>
